package org.morningangel.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.Date;

public class SendSecurityCodeUtil {
	public static String send(String phone) {
		System.out.println("电话：" + phone);
		/*产生随机数*/
		String randCode=getRandomCode();
		System.out.println("产生的随机数为:"+randCode);
		StringBuilder content=new StringBuilder("您好，您的注册验证码是:"+randCode);
		/*获取验证时间*/
		Date date=new Date();
		String time=DateFormat.getDateInstance().format(date);
		content.append("验证时间"+time);
		
		StringBuilder sb=new StringBuilder();
		sb.append("http://www.gysoft.cn/smspost_utf8/send.aspx?");
		
		//发送客户账号密码
		sb.append("username=ljt_cherish");
		sb.append("&password=morningangel");

		//发送的手机号
		sb.append("&mobile="+phone);
		
		//将字符编码强制转换
		try {
			sb.append("&content="+URLEncoder.encode(content.toString(),"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		System.out.println("请求内容:"+sb.toString());
		try {
			URL url=new URL(sb.toString());

			HttpURLConnection  con=(HttpURLConnection)url.openConnection();
			con.setRequestMethod("POST");
			
			
			BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream()));
			String result=reader.readLine();
			System.out.println("返回结果:"+result);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("出错啦:"+e.toString());
			return "0";//表示获取验证码失败
		}
		return randCode;
	}
	 /*随机生成5位0~9随机数*/
	 public static String getRandomCode(){
			StringBuilder sb=new StringBuilder();
			Long b=0L;
			for(int i=0;i<5;i++){
				b=Math.round(Math.floor(Math.random()*9));
			    sb.append(b);
			}
			return sb.toString();
		}
}
